<?php
/*
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-04 16:54:35
 * @LastEditTime: 2023-10-11 16:00:45
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @Description: 
 * 函数定义protected  出错，mysql会自动rollback
 */

namespace App\Http\Services;

use Exception;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\DB;
use App\Events\SubscribeEvent;
use Maatwebsite\Excel\Facades\Excel;

class Service
    {
    public $repository;

    public function __construct()
        {
        if (method_exists($this, 'boot')) {
            App::call([$this, 'boot']);
            }
        }
    protected function enable()
        {
        $data = $this->repository->whereIn("id", $this->getRequestIds())->first();
        if ($data->status_id == 0)
            fail("单据【{$data->code}】已启用！");
        return enable($data);
        }

    protected function disable()
        {
        $data = $this->repository->whereIn("id", $this->getRequestIds())->first();
        if ($data->status_id == -1)
            fail("单据【{$data->code}】未启用！");
        return enable($data, false);
        }


    public function __call($name, $arguments)
        {
        $methodVariable = array($this, $name);
        $res            = ['code' => 200, 'data' => null];
        if (method_exists($this, $name)) {
            if (is_callable($methodVariable, true))
                try {
                    $res['data'] = DB::transaction(function () use ($name, $arguments)
                        {
                        return $this->$name(...$arguments);
                        }, 3);

                    return $res['data'];
                    }
                catch ( Exception $e ) {
                    $res['data'] = $e;
                    $res['code'] = 500;
                    fail($e->getMessage());
                    }
                finally {
                    //异步调用事件
                    $this->callEvent($res);
                    }
            }
        else {
            fail("禁止访问");
            }
        }

    /**
     * callEvent function
     *
     * @param [type] $res
     * @param [type] $eventName 默认是订阅事件
     * @return void
     */
    private function callEvent($res, $eventName = SubscribeEvent::class)
        {
        $api = app("api");

        $event_params = ['data' => $res, 'router' => $api, 'token' => app('token')];

        $evt = $this->getEventClass($event_params);

        if ($evt != false && count($evt->listeners) > 0) {
            event($evt);
            }
        event($this->getEventClass($event_params, $eventName));
        }
    //构造验证方法
    private function getEventClass($params = [], $class = null)
        {
        $CLS = $class == null ? getEvent() : $class;

        if (class_exists($CLS))
            return App::make($CLS, $params);
        return false;
        }
    public static function __callStatic($name, $arguments)
        {
        return (App::make(static::class))->$name(...$arguments);
        }

    public static function run($name, $arguments = [])
        {
        return (App::make(static::class))->$name(...$arguments);
        }


    public function getRequestIds()
        {
        $request = request();
        $ids     = [];
        if ($request->has("removeRecords")) {
            array_filter($request->input("removeRecords"), function ($item) use (&$ids)
                {
                $ids[] = $item['id'];
                });
            }
        if ($request->has("ids")) {
            $ids = $request->input("ids");
            }
        if ($request->has("id")) {
            $ids[] = $request->input("id");
            }
        return $ids;
        }
    public function getFilter($name = null)
        {
        $res     = null;
        $request = request();
        if ($request->has("filter")) {
            $filters = $request->filter;
            foreach ($filters ?? [] as $keys => $filter) {
                foreach ($filter ?? [] as $key => $value)
                    if ($key == $name) {
                        $res = $filters[$keys][$name];
                        unset($filters[$keys][$name]);
                        break;
                        }
                }

            $request->offsetSet("filter", $filters);
            }
        return $res;
        }
    public function OnPrintEnd()
        {
        }
    public function import()
        {
        $file   = request()->file('file');
        $import = getImport();
        Excel::import(App::make($import), $file);
        }

    protected function setRowColor()
        {
        fail("未设置颜色，无法保存数据");
        }
    }
